// miniprogram/pages/mdshow/mdshow.js
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        enablePoster: false,
        linkIsFirstTap: true,

        isOverTile: false,
        navigationBarHeight: 40,
        isDark: false,

        id: '',
        title: '',             // optional
        url: '',
        showComment: false,    // optional
        commentSensitiveWords: [],

        articleData: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
        
        that.data.id = options.id;
        that.data.title = options.title;
        that.data.url = options.url;
        that.data.showComment = options.enable_comment == 'true' ? true : false;
        if (app.globalData.config.global.comment_filter) {
            that.setData({
                commentSensitiveWords: app.globalData.config.global.comment_filter
            })
        }

        if (app.globalData.systemInfo) {
            that.data.navigationBarHeight = app.globalData.systemInfo.screenHeight - app.globalData.systemInfo.windowHeight - app.globalData.systemInfo.statusBarHeight;
        } else {
            let systemInfo = wx.getSystemInfoSync();
            app.globalData.systemInfo = systemInfo;
            that.data.navigationBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - systemInfo.statusBarHeight;
        }
        
        // 检查NewWxComment显示设置
        if (app.globalData.config) {
            if (!app.globalData.config.global.comment) {
                that.data.showComment = false;
            }
        }

        that.setData({
            id: that.data.id,
            title: that.data.title,
            showComment: that.data.showComment
        })

        that.fetechArticleData();
    },
    // towxml 绑定tap事件处理
    __bind_tap: function (event) {
        //console.log(event);
        let that = this;
        // 隐藏评论组件菜单栏
        if (this.data.showComment) {
            let newWxComment = this.selectComponent('#NewWxComment');
            newWxComment.hiddenMenubox();
        }

        if (that.data.linkIsFirstTap) {
            // Bug: 会触发两次tap
            // 处理图片预览功能
            if (event.target.dataset._el.tag == "image") {
                wx.previewImage({
                    current: event.target.dataset._el.attr.src, //当前图片地址
                    urls: [event.target.dataset._el.attr.src],  //所有要预览的图片的地址集合 数组形式
                    success: function (res) {

                    },
                    fail: function (res) {

                    },
                    complete: function (res) {

                    },
                })
                return;
            }

            // 处理内部链接
            let link = event.target.dataset._el.attr.href;
            if (!link) {
                // space click handle
                return;
            }
            let link_item_list = link.split('.');
            let link_type = link_item_list[link_item_list.length - 1];
            //console.log(link_type);
            if (link_type == 'htm' || link_type == 'html') {
                wx.showModal({
                    title: '提示',
                    content: '个人小程序不支持打开外部链接！',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            // 复制到黏贴板
                            wx.setClipboardData({
                                data: link,
                                success(res) {

                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                })
            } else if (link_type == 'md') {
                console.log('内部md链接');
                // TODO
            } else {
                wx.showModal({
                    title: '提示',
                    content: '个人小程序不支持打开外部链接！',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            // 其他非htm/html/md后缀链接
                            // 复制到黏贴板
                            wx.setClipboardData({
                                data: link,
                                success(res) {

                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                })
            }
        }
        that.data.linkIsFirstTap = false;
        setTimeout(function () {
            that.data.linkIsFirstTap = true;
        }, 1000);
    },
    fetechArticleData: function () {
        let that = this;
        wx.showLoading({
            title: '加载中...',
        })
        setTimeout(function () {
            wx.hideLoading()
        }, 8000)
        wx.request({
            url: that.data.url,
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                if (res.statusCode != 200) {
                    wx.hideLoading();
                    wx.showToast({
                        title: '加载MD数据失败',
                        icon: 'none',
                        duration: 2000
                    })
                    return;
                }
                //console.log(res)
                console.log('请求MD数据成功');
                let output = app.base64.decode(res.data.content);
                // 将markdown内容转换为towxml数据
                let md_data = app.towxml.toJson(output, 'markdown');

                // 设置文档显示主题，默认'light'
                md_data.theme = 'light';
                that.setData({
                    articleData: md_data
                });
                wx.hideLoading();
            },
            fail: function (e) {
                console.log(e)
                console.log('请求MD数据失败');
                wx.hideLoading();
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        console.log('onReachBottom');
        if (this.data.showComment) {
            let newWxComment = this.selectComponent('#NewWxComment');
            newWxComment.onReachBottom();
        }
    },
    onPageScroll(e) {
        let that = this;
        //console.log(e.scrollTop);
        if (e.scrollTop >= that.data.navigationBarHeight && !that.data.isOverTile) {
            that.data.isOverTile = true;
            wx.setNavigationBarTitle({
                title: that.data.title
            })
        } else if (e.scrollTop < that.data.navigationBarHeight && that.data.isOverTile) {
            that.data.isOverTile = false;
            wx.setNavigationBarTitle({
                title: ''
            })
        } else {
            // nothing to do
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})